package com.dz.gateway.filter;

import java.io.ByteArrayInputStream;

import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson.JSON;
import com.dz.common.web.ResultVO;
import com.netflix.zuul.context.RequestContext;

@Slf4j
public class ErrorFilter extends AbstractResponseFilter {

	public boolean shouldFilter() {
		RequestContext ctx = RequestContext.getCurrentContext();
		// only forward to errorPath if it hasn't been forwarded to already
		return ctx.containsKey("error.status_code") && !ctx.getBoolean(SEND_ERROR_FILTER_RAN, false);
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		int statusCode = (Integer) ctx.get("error.status_code");
		String message = null;
		if (ctx.containsKey("error.exception")) {
			Object e = ctx.get("error.exception");
			log.warn("Error during filtering", Throwable.class.cast(e));
		}
		if (ctx.containsKey("error.message")) {
			message = (String) ctx.get("error.message");
		}
		HttpServletResponse servletResponse = ctx.getResponse();
		if (servletResponse.getCharacterEncoding() == null) { // only set if not
			servletResponse.setCharacterEncoding("UTF-8");
		}
		try {
			ResultVO resultVO = new ResultVO(statusCode, null, message);
			writeResponse(new ByteArrayInputStream(JSON.toJSONString(resultVO).getBytes("utf-8")), ctx.getResponse()
					.getOutputStream());
		} catch (Exception e) {
			log.error("push out error", e);
		}
		return null;
	}

	@Override
	public String filterType() {
		return "post";
	}

	@Override
	public int filterOrder() {
		return 0;
	}
}
